#include "tcp_socket_io.h"

int read_int(int sockfd, int *n){
  int tmp;
  if(readn(sockfd, &tmp, sizeof(int))!=sizeof(int))
    return -1;
  *n = (int)ntohl((uint32_t)tmp);
  return (sizeof(int));
}

int read_string(int sockfd, char *str, int max){
  int num_bytes;
  if((num_bytes=readn(sockfd, str, max*sizeof(char)))<0)
    return -1;
  return num_bytes;
}

int readn(int sockfd, void *buf, int n){
  int num_bytes, total = n;
  do{
    num_bytes=read(sockfd, buf, n);
    if(num_bytes<0){
      if(errno!=EINTR)
	return -1;
    }else if(num_bytes==0){
      return (total-n);
    }else{
      buf += num_bytes;
      n -= num_bytes;
    }
  }while(n!=0);
  return total;
}

int write_int(int sockfd, int n){
  n = htonl((uint32_t)n);
  if(write(sockfd, &n, sizeof(int))!=sizeof(int))
    return -1;
  return (sizeof(int));
}

int write_string(int sockfd, char *str, int max){
  int num_bytes;
  if((num_bytes=write(sockfd, str, max*sizeof(char)))<0)
    return -1;
  return num_bytes;
}

int writen(int sockfd, void *buf, int n){
  int num_bytes, total = n;
  do{
    num_bytes=write(sockfd, buf, n);
    if(num_bytes<0){
      if(errno!=EINTR)
	return -1;
    }else if(num_bytes==0){
      return -1;
    }else{
      buf += num_bytes;
      n -= num_bytes;
    }
  }while(n!=0);
  return total;
}
